import { login, getProfile, getUserDetailById } from '@/api/user'
import router from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  // token: localStorage.getItem('token') || ''
  token: getToken() || '',
  profile: {}
}
const mutations = {
  setToken(state, data) {
    // localStorage.setItem('token', data)
    setToken(data)
    state.token = data
  },
  setProfile(state, data) {
    state.profile = data
  },
  removeToken(state) {
    removeToken()
    state.token = ''
  },
  removeProfile(state) {
    state.profile = {}
  }
}
const actions = {
  async login(store, data) {
    const res = await login(data)
    // console.log(res.data.data)
    store.commit('setToken', res)
    localStorage.setItem('loginTime', Date.now())
  },
  async getProfile(store) {
    const res = await getProfile()
    // store.commit('setProfile', res)
    const detail = await getUserDetailById(res.userId)
    store.commit('setProfile', {
      ...res,
      ...detail
    })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeProfile')
    router.push('login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

